<?php
class UserDAL {
	private $userTableName = "Member";
	private $myConnection = NULL;

	public function __construct(DBConnection $connection) {
		$this -> myConnection = $connection;
	}

	/**
	 * CREATE TABLE `labbar`.`Member` (`pk` INT NOT NULL  AUTO_INCREMENT,
	 * `username` VARCHAR( 50 ) NOT NULL ,
	 * `password` VARCHAR( 50 ) NOT NULL ,
	 * PRIMARY KEY ( `pk` )
	 ) ENGINE = INNODB;
	 *
	 */

	public function userExists($username) {
		// Returns true if passed username exists, else false
		$sql = "SELECT * FROM $this->userTableName WHERE Username = ?";
		$stmt = $this -> myConnection -> prepare($sql);
		$stmt -> bind_param("s", $username);
		$stmt -> execute();
		if ($stmt -> fetch()) {
			return TRUE;
		} else {
			return FALSE;
		}
		$stmt -> close();
	}

	public function checkPassword($username, $password) {
		// Returns true of input username and password are a match
		$sql = "SELECT * FROM $this->userTableName WHERE Username = ? AND Password = ?";
		$stmt = $this -> myConnection -> prepare($sql);
		$stmt -> bind_param("ss", $username, $password);
		$stmt -> execute();
		$stmt -> store_result();
		$rows = $stmt -> num_rows();
		$stmt -> close();
		if ($rows === 1) {
			return true;
		} else {
			return false;
		}
	}

	public function getUsers() {
		$ret = array();
		$sql = "SELECT Username FROM $this->userTableName";
		$stmt = $this -> myConnection -> prepare($sql);
		$stmt -> execute();
		/* bind result variables */
		$stmt -> bind_result($name);
		/* fetch values */
		while ($stmt -> fetch()) {
			$ret[] = $name;
		}
		$stmt -> close();
		return $ret;
	}

	public function addUser($username, $password) {
		$pk = NULL;
		$validation = new validate();
		// If username and password are valid, add user to database
		if ($validation -> validateUsername($username) && $validation -> validatePassword($password)) {
			$sql = "INSERT INTO " . $this -> userTableName . " VALUES(?, ?, ?)";
			$stmt = $this -> myConnection -> prepare($sql);
			$stmt -> bind_param("sss", $pk, $username, $password);
			$ret = $stmt -> execute();
			$stmt -> close();
			return $ret;
		} else {
			return false;
		}
	}

	public function deleteUser($username) {
		$sql = "DELETE FROM " . $this -> userTableName . " WHERE Username = ?";
		$stmt = $this -> myConnection -> prepare($sql);
		$stmt -> bind_param("s", $username);
		$ret = $stmt -> execute();
		$stmt -> close();
		return $ret;
	}

}
